/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tolls;

import avenue.Avenue;
import avenue.Session;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import model.Card;
import model.Collection;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;
import model.VehicleCategory;

/**
 *
 * @author Vasilis Bourloumis
 */
public class CollectTollForm extends javax.swing.JFrame {
    private EntityManager em;
    private Card card;
    private Avenue parent;
    /**
     * Creates new form CollectTollForm
     */
    public CollectTollForm(Avenue parent) {
        this.parent = parent;
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jButton1.setText("ΔΙΕΛΕΥΣΗ");
        jButton1.setEnabled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Αρ. Κάρτας: ");

        jLabel1.setText("Αρ. Κυκλοφορίας: ");

        jButton2.setText("ΠΛΗΡΩΜΗ");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Υπόλοιπο Κάρτας: ");

        jTextField3.setEnabled(false);

        jButton3.setText("Εμφάνιση Υπολοίπου");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Άκυρο");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel4.setText("Πλήθος Διελεύσεων: ");

        jTextField4.setEnabled(false);

        jLabel5.setText("Κόστος Διέλευσης: ");

        jTextField5.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 566, Short.MAX_VALUE)
                        .addComponent(jButton4))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(14, 14, 14)
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jButton3)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel1)
                                            .addComponent(jLabel2))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // instantiate card
        String regNumber = "";
        int cardId = 0;
        try{
            regNumber = this.jTextField1.getText();
            cardId = Integer.parseInt(this.jTextField2.getText());
            card = em.createNamedQuery("Card.findById", Card.class).setParameter("id", cardId).getSingleResult();
            if( card.belongsCardToVehicle(cardId, regNumber) ){
                Double balance = card.getBalance();
                this.jTextField3.setText(balance.toString());
                this.jButton2.setEnabled(true);
                if( balance < 10 ){
                    JOptionPane.showMessageDialog(this, "Το υπόλοιπο της κάρτας είναι μικρότερο του 10. Επιθυμείτε πληρωμή;");
                }
                double cost = checkBalance(balance);
                this.jTextField5.setText(cost+"");
            } else {
                throw new Exception("Το Όχημα με Αριθμό Κυκλοφορίας:"+regNumber+" δεν έχει Κάρτα με αριθμό:"+cardId);
            }
        } catch(NumberFormatException e){
            JOptionPane.showMessageDialog(this, "Ο αριθμός Kάρτας θα πρέπει να είναι ακέραιος αριθμός.");
        } catch(NoResultException e){
            JOptionPane.showMessageDialog(this, "Δε βρέθηκε Kάρτα με αριθμό: "+cardId);
        } catch(Exception e){
            JOptionPane.showMessageDialog(this, "Δεν βρέθηκε ο Αρ. Κυκλοφορίας του αυτοκινήτου.");
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        PaymentForm pf = new PaymentForm(this, card);
        this.setEnabled(false);
        pf.setVisible(true);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        Collection collection = new Collection();
        em.persist(collection);
        collection.setPassTimestamp(new Date());
        BigDecimal cost = new BigDecimal(this.jTextField5.getText());
        collection.setTollCollected(cost);
        collection.setCardId(card);
        if( this.card.getCollectionList() == null ){
            List<Collection> collections = new ArrayList<Collection>();
            collections.add(collection);
            this.card.setCollectionList(collections);
        } else {
            this.card.getCollectionList().add(collection);
        }
        this.card.setBalance(this.card.getBalance()-cost.doubleValue());
        em.getTransaction().commit();
        this.parent.setEnabled(true);
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        this.parent.setEnabled(true);
        dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration//GEN-END:variables

    public double checkBalance(Double balance){
        // program rate
        VehicleCategory categoryId = this.card.getVehicleList().getCategoryId();
        Program programId = this.card.getProgramId();
        Station stationId = Session.loginUser.getStationId();
        ProgramRate pr = em.createNamedQuery("ProgramRate.findRate", ProgramRate.class)
                .setParameter("categoryId", categoryId)
                .setParameter("programId", programId)
                .setParameter("stationId", stationId)
                .getSingleResult();
        double cost = pr.getRate().doubleValue();
        
        int freePasses = this.card.getProgramId().getFreePasses();
        int freePassesReq = this.card.getProgramId().getFreePassesRequirement();
        int numberOfPasses = this.card.getNumberOfPassesThisMonth();
        this.jTextField4.setText(numberOfPasses+"");
        
        if( freePasses > 0 && freePassesReq <= numberOfPasses ){
            this.jButton1.setEnabled(true);
            return 0;
        } else if(  balance < cost ){
            JOptionPane.showMessageDialog(this, "Το υπόλοιπο δεν επαρκή για διέλευση (διόδια = "+cost+"). Απαιτείται πληρωμή.");
            return cost;
        } else {
            this.jButton1.setEnabled(true);
            return cost;
        }
    }

    public void setjTextField3(String amount) {
        this.jTextField3.setText(amount);
    }

    public void enablePassButton() {
        this.jButton1.setEnabled(true);
    }
    
    

}
